<template>
  <div class="container">
    <h2>Raccoon Guide</h2>
    <h2>Register</h2>
    <!-- Registration Form -->
    <form @submit.prevent="handleRegister">
      <div class="form-group">
        <label for="userName">userName</label>
        <input type="text" id="userName" v-model="userName" required />
      </div>
      <div class="form-group">
        <label for="password">Password</label>
        <input type="password" id="password" v-model="password" required />
      </div>
      <button type="submit">Register</button>
    </form>
    <p>
      Already have an account? 
      <router-link to="/login">Login here</router-link>
    </p>
    
    <!-- Toast Notification -->
    <div v-if="showToast" class="toast">Registration Successful! Redirecting to login...</div>
  </div>
</template>

<script lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';

export default {
  name: 'Register',
  setup() {
    const userName = ref('');
    const password = ref('');
    const showToast = ref(false);
    const router = useRouter();

    // Handle registration form submission
    const handleRegister = async () => {
      try {
        const response = await fetch('http://localhost:7777/register', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            userName: userName.value,
            password: password.value,
          }),
        });

        const data = await response.json();

        if (response.ok) {
          // Registration successful, show toast and redirect to login
          showToast.value = true;
          setTimeout(() => {
            showToast.value = false;
            router.push('/login'); // Redirect to login page after 3 seconds
          }, 3000);
        } else {
          // Registration failed, show error message
          alert(data.message || 'Registration failed');
        }
      } catch (error) {
        console.error('Registration failed:', error);
        alert('An error occurred. Please try again.');
      }
    };

    return {
      userName,
      password,
      handleRegister,
      showToast,
    };
  },
};
</script>

<style scoped>
/* Container styles */
.container {
  width: 300px;
  margin: 0 auto;
  padding: 20px;
  text-align: center;
}

.form-group {
  margin-bottom: 15px;
}

/* Input styles */
input {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

/* Submit button styles */
button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

/* Toast notification styles */
.toast {
  margin-top: 15px;
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border-radius: 4px;
}
</style>
